package fun

import (
	"fmt"
	"reflect"
	"strings"
)

func StructToArr(data interface{}) []map[string]interface{} {
	arr := make([]map[string]interface{}, 0)
	t := reflect.TypeOf(data)

	for k := 0; k < t.NumField(); k++ {
		structField := t.Field(k)
		tag := structField.Tag
		fieldInfo := map[string]interface{}{
			"Field":    structField.Name,
			"DataType": structField.Type.String(),
		}

		// 将标签字符串按空格分割，获取所有键值对
		tags := strings.Fields(fmt.Sprintf("%q", tag))
		for _, tagStr := range tags {
			// 检查字符串是否以引号开始和结束，如果是，则去掉引号
			if len(tagStr) > 2 && tagStr[0] == '"' && tagStr[len(tagStr)-1] == '"' {
				tagStr = tagStr[1 : len(tagStr)-1]
			}
			// 分割键和值
			splitTag := strings.SplitN(tagStr, ":", 2)
			if len(splitTag) == 2 {
				key := strings.TrimSpace(splitTag[0])
				value := strings.TrimSpace(splitTag[1])

				// 清理值：去除多余的双引号和转义字符
				cleanValue := StrReplace(value, `"`, "")
				cleanValue = StrReplace(value, `\`, "")
				cleanValue = StrReplace(cleanValue, `"`, "")

				if key != "" && cleanValue != "" {
					// 移除键名后的冒号和空格
					key = strings.TrimSuffix(key, ":")
					fieldInfo[key] = cleanValue
				}
			}
		}

		arr = append(arr, fieldInfo)
	}

	return arr
}
